/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.yangxu.hospital.system.modules.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.yangxu.hospital.common.utils.PageResult;
import com.yangxu.hospital.common.utils.PageUtil;
import com.yangxu.hospital.logging.annotation.Log;
import com.yangxu.hospital.system.modules.system.domain.Menu;
import com.yangxu.hospital.system.modules.system.domain.SysDepartment;
import com.yangxu.hospital.system.modules.system.service.SysDepartmentService;
import com.yangxu.hospital.system.modules.system.domain.vo.SysDepartmentQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.util.*;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
* @author 杨旭
* @date 2024-11-25
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "科室管理管理")
@RequestMapping("/api/sysDepartment")
public class SysDepartmentController {

    private final SysDepartmentService sysDepartmentService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('sysDepartment:list')")
    public void exportSysDepartment(HttpServletResponse response, SysDepartmentQueryCriteria criteria) throws IOException {
        sysDepartmentService.download(sysDepartmentService.queryAll(criteria), response);
    }

    @ApiOperation("返回全部的科室")
    @GetMapping(value = "/lazy")
    @PreAuthorize("@el.check('sysDepartment:list')")
    public ResponseEntity<List<SysDepartment>> queryAllMenu(@RequestParam Long pid){
        return new ResponseEntity<>(sysDepartmentService.getDepartment(pid),HttpStatus.OK);
    }

    @GetMapping
    @Log("查询科室管理")
    @ApiOperation("查询科室管理")
    @PreAuthorize("@el.check('sysDepartment:list')")
    public ResponseEntity<PageResult<SysDepartment>> querySysDepartment(SysDepartmentQueryCriteria criteria) throws Exception {
        List<SysDepartment> sysDepartments = sysDepartmentService.queryAll(criteria, true);
        return new ResponseEntity<>(PageUtil.toPage(sysDepartments),HttpStatus.OK);
    }

    @ApiOperation("查询菜单:根据ID获取同级与上级数据")
    @PostMapping("/superior")
    @PreAuthorize("@el.check('sysDepartment:list')")
    public ResponseEntity<List<SysDepartment>> getDepartmentSuperior(@RequestBody List<Long> ids) {
        Set<SysDepartment> departments = new LinkedHashSet<>();
        if(CollectionUtil.isNotEmpty(ids)){
            for (Long id : ids) {
                SysDepartment sysDepartment = sysDepartmentService.findById(id);
                List<SysDepartment> list = sysDepartmentService.getSuperior(sysDepartment, new ArrayList<>());
                for (SysDepartment data : list) {
                    if(data.getDepartmentId().equals(sysDepartment.getParentId())) {
                        data.setSubCount(data.getSubCount() - 1);
                    }
                }
                departments.addAll(list);
            }
            // 编辑菜单时不显示自己以及自己下级的数据，避免出现PID数据环形问题
            departments = departments.stream().filter(i -> !ids.contains(i.getDepartmentId())).collect(Collectors.toSet());
            return new ResponseEntity<>(sysDepartmentService.buildTree(new ArrayList<>(departments)),HttpStatus.OK);
        }
        return new ResponseEntity<>(sysDepartmentService.getDepartment(null),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增科室管理")
    @ApiOperation("新增科室管理")
    @PreAuthorize("@el.check('sysDepartment:add')")
    public ResponseEntity<Object> createSysDepartment(@Validated @RequestBody SysDepartment resources){
        sysDepartmentService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改科室管理")
    @ApiOperation("修改科室管理")
    @PreAuthorize("@el.check('sysDepartment:edit')")
    public ResponseEntity<Object> updateSysDepartment(@Validated @RequestBody SysDepartment resources){
        sysDepartmentService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除科室管理")
    @ApiOperation("删除科室管理")
    @PreAuthorize("@el.check('sysDepartment:del')")
    public ResponseEntity<Object> deleteSysDepartment(@RequestBody Set<Long> ids) {
        Set<SysDepartment> sysDepartmentSet = new HashSet<>();
        // 看看传来的是不是一级，是最上级就一起把下面的删除了
        // 二级就删除后，更新一级的数量
        for (Long id : ids) {
            List<SysDepartment> department = sysDepartmentService.getDepartment(id);
            sysDepartmentSet.add(sysDepartmentService.getById(id));
            sysDepartmentSet = sysDepartmentService.getchildDepartment(department, sysDepartmentSet);

        }
//        sysDepartmentService.deleteAll(ids);
        sysDepartmentService.delete(sysDepartmentSet);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}